#include "customslider.h"
#include "models/command.h"
#include "qdebug.h"
CustomSlider::CustomSlider(QWidget *parent)
    : QSlider(Qt::Horizontal, parent)
{
    // setStyleSheet(
    //     QString(
    //         "QSlider {"
    //         "    min-height: %1px;"
    //         "    max-height: %2px;"
    //         "}"
    //         "QSlider::groove:horizontal {"
    //         "    background: #1F1F1F;"
    //         "    height: %3px;"
    //         "    border-radius: %4px;"
    //         "    margin: %5px 0;"
    //         "}"
    //         "QSlider::handle:horizontal {"
    //         "    background: transparent;"
    //         "    width: %6px;"
    //         "    margin: %7px 0;"
    //         "}"
    //         ).arg(int(15*g_xScale))
    //         .arg(int(40*g_xScale))
    //         .arg(int(10*g_xScale))
    //         .arg(int(5*g_xScale))
    //         .arg(int(15*g_xScale))
    //         .arg(int(25*g_xScale))
    //         .arg(int(-20*g_xScale))
    //     );
    
    QSlider::setRange(0, 1000);
    connect(this,&QSlider::valueChanged,this,[this](int value){emit floatValueChanged(value * 0.1);});
}

void CustomSlider::setFloatRange(float min, float max)
{
    m_min = min;
    m_max = max;
    QSlider::setRange(scaleToInt(min), scaleToInt(max));
}

void CustomSlider::setFloatValue(float value)
{
    QSlider::setValue(scaleToInt(value));
}

float CustomSlider::floatValue() const
{
    return scaleToFloat(value());
}

int CustomSlider::scaleToInt(float value) const
{
    return qRound(value * SCALE_FACTOR);
}

float CustomSlider::scaleToFloat(int value) const
{
    return static_cast<float>(value) / SCALE_FACTOR;
}

void CustomSlider::paintEvent(QPaintEvent *ev)
{
    QSlider::paintEvent(ev);
    
    if (m_showValue) {
        QPainter painter(this);
        painter.setRenderHint(QPainter::Antialiasing);
        
        double ratio = (value() - minimum()) / static_cast<double>(maximum() - minimum());
        int handleX = ratio * (width() - 25*g_xScale) + 12*g_xScale;
        painter.setPen(Qt::white);
        QFont font;
        font.setFamily("微软雅黑");
        font.setPixelSize(16*g_xScale);
        QString valueText = QString::number(floatValue(), 'f', 1);
        QFontMetrics fm(painter.font());
        QRect textRect = fm.boundingRect(valueText);
        painter.drawText(handleX - textRect.width()/2,
                         16*g_xScale,
                         valueText);
    }
}
